<template>
  <a-modal title="项目信息" :visible="show" @ok="handleOk" @cancel="handleCancel" width="70vw" :maskClosable="false">
    <div v-if="edit">
      <a-button @click="openPurchaseOrderList" icon="search" class="hte-btn">获取采购订单</a-button>
      <a-button @click="deletePurchaseOrderList" icon="delete" class="hte-btn">删除明细行</a-button>
      <a-button @click="changeSettlementType" icon="diff" class="hte-btn">计算</a-button>
      <a-button @click="savePurchaseOrderList" icon="check" class="hte-btn">保存</a-button>
    </div>
    <div>
      <a-form-model ref="checkListForm">
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="结算金额">
              <a-input :disabled="!edit" v-model="settlement.settlementAmount" @change="changeSettlementType" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="其他扣减项">
              <a-input :disabled="!edit" v-model="settlement.deductAmount" @change="changeSettlementType" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="核算单号">
              <a-input v-model="settlement.settlementNum" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="质保金计算方式">
              <a-select :disabled="!edit" v-model="settlement.settlementType" @change="changeSettlementType">
                <a-select-option v-for="(code, index) in WorkReportCheckListType" :value="code.code" :key="index">
                  {{ code.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="质保金比例(%)">
              <a-input :disabled="!edit" v-model="settlement.qualityDepositRatio" @change="changeSettlementType" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="本次支付金额">
              <a-input v-model="settlement.paymentAmount" :disabled="!(settlement.checkType == '3') || !edit" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item label="备注">
              <a-input :disabled="!edit" v-model="settlement.remark" type="textarea" rows="2" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <div style="height: 360px; overflow: scroll">
      <a-table
        :columns="detailColumns"
        :data-source="records"
        :rowKey="
          (record, index) => {
            return index
          }
        "
        bordered
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      >
        <span slot="paidAmountRender" slot-scope="text, record">
          <a-input v-model="record.paidAmount" :disabled="!edit" @change="changeSettlementType" />
        </span>
        <span slot="unpaidAmountRender" slot-scope="text, record">
          <a-input v-model="record.unpaidAmount" :disabled="!edit" @change="changeSettlementType" />
        </span>
        <span slot="qualityDepositRender" slot-scope="text, record">
          <a-input v-model="record.qualityDeposit" :disabled="!edit" @change="changeSettlementType" />
        </span>
        <span slot="finalQualityDepositRender" slot-scope="text, record">
          <a-input
            v-model="record.finalQualityDeposit"
            @change="changeSettlementType"
            :disabled="settlement.settlementType != '3' || !edit"
          />
        </span>
      </a-table>
    </div>
    <div style="display: flex; justify-content: flex-end">
      <span style="padding: 5px 5px"> 行项总额：{{ totalObj.fundAmountTotal }} </span>
      <span style="padding: 5px 5px"> 已支付总额：{{ totalObj.paidAmountTotal }} </span>
      <span style="padding: 5px 5px"> 已发起但未支付总额：{{ totalObj.unpaidAmountTotal }} </span>
      <span style="padding: 5px 5px"> 质保金总额：{{ totalObj.qualityDepositTotal }} </span>
      <span style="padding: 5px 5px"> 最终预留质保金总额：{{ totalObj.finalQualityDepositTotal }} </span>
    </div>
    <PurchaseOrderList :show="showPurchaseOrderList" :supplierCode="supplierCode" :wbs="wbs" @selected="selected" />
  </a-modal>
</template>
<script>
import { postAction,getAction } from '@/api/manage'
import PurchaseOrderList from '@/views/workReport/purchase/PurchaseOrderList'
export default {
  components: {
    PurchaseOrderList,
  },
  props: {
    show: {
      type: Boolean,
      default: false,
    },
    taskInfoId: {
      type: String,
      default: null,
    },
    supplierCode: {
      type: String,
      default: null,
    },
    wbs: {
      type: String,
      default: null,
    },
    edit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      detailColumns: [
        {
          title: '采购订单号',
          // dataIndex: 'EBELN',
          dataIndex: 'purchaseOrderNum',
          width: '100px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '合同号',
          // dataIndex: 'DOKNR',
          dataIndex: 'contractNum',
          width: '150px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '项目行号',
          // dataIndex: 'EBELP',
          dataIndex: 'lineNum',
          width: '80px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '款项名称',
          // dataIndex: 'TXZ01',
          dataIndex: 'fundName',
          width: '300px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '行项金额',
          // dataIndex: 'NETPR',
          dataIndex: 'fundAmount',
          width: '160px',
          align: 'center',
          ellipsis: true,
        },
        {
          title: '已付金额',
          // dataIndex: 'DMBTR',
          dataIndex: 'paidAmount',
          width: '160px',
          align: 'center',
          scopedSlots: { customRender: 'paidAmountRender' },
        },
        {
          title: '已发起单未支付金额',
          dataIndex: 'unpaidAmount',
          width: '180px',
          align: 'center',
          scopedSlots: { customRender: 'unpaidAmountRender' },
        },
        {
          title: '质保金额',
          dataIndex: 'qualityDeposit',
         width: '160px',
          align: 'center',
          scopedSlots: { customRender: 'qualityDepositRender' },
        },
        {
          title: '最终预留质保金',
          dataIndex: 'finalQualityDeposit',
          width: '160px',
          align: 'center',
          scopedSlots: { customRender: 'finalQualityDepositRender' },
        },
      ],
      WorkReportCheckListType: [
        { code: '1', name: 'A:最终预留质保金=结算金额*质保金比例' },
        { code: '2', name: 'B:最终预留质保金=质保金额' },
        { code: '3', name: 'C:最终预留质保金=人工编辑' },
      ],
      urls: {
        loadPurchaseOrderDetail: '/hte/contract/loadPurchaseOrderDetail',
        info: '/workReport/task/settlement/info',
        save: '/workReport/task/settlement/edit',
      },
      showPurchaseOrderList: false,
      selectedRowKeys: [],
      selectedRow: [],
      records: [{}, {}],
      settlement: { details: [], qualityDepositRatio: 100 },
      totalObj: {},
    }
  },
  computed: {
    showFlag() {
      return this.show
    },
  },
  mounted() {
    this.fetchSettlement()
    this.calcTotalObj()
  },
  methods: {
    fetchSettlement() {
      if (this.taskInfoId) {
        getAction(this.urls.info + '/' + this.taskInfoId).then((res) => {
          if (res.success) {
            this.settlement = res.result
            if (!this.settlement) {
              this.settlement = { details: [] }
            }
            this.records = this.settlement.details
            this.calcTotalObj()
          } else {
            this.$messageWorkReport.success(res.message)
          }
        })
      }
    },
    calcTotalObj() {
      let fundAmountTotal = 0
      let paidAmountTotal = 0
      let unpaidAmountTotal = 0
      let qualityDepositTotal = 0
      let finalQualityDepositTotal = 0
      if (this.records) {
        this.records.forEach((r) => {
          if (r.fundAmount) {
            fundAmountTotal += parseFloat(r.fundAmount)
          }
          if (r.paidAmount) {
            paidAmountTotal += parseFloat(r.paidAmount)
          }
          if (r.unpaidAmount) {
            unpaidAmountTotal += parseFloat(r.unpaidAmount)
          }
          if (r.qualityDeposit) {
            qualityDepositTotal += parseFloat(r.qualityDeposit)
          }
          if (r.finalQualityDeposit) {
            finalQualityDepositTotal += parseFloat(r.finalQualityDeposit)
          }
        })
      }
      let total = {}
      total.fundAmountTotal = fundAmountTotal.toFixed(2)
      total.paidAmountTotal = paidAmountTotal.toFixed(2)
      total.unpaidAmountTotal = unpaidAmountTotal.toFixed(2)
      total.qualityDepositTotal = qualityDepositTotal.toFixed(2)
      total.finalQualityDepositTotal = finalQualityDepositTotal.toFixed(2)
      this.totalObj = total
    },
    openPurchaseOrderList() {
      this.showPurchaseOrderList = true
    },
    deletePurchaseOrderList() {
      let list = []
      this.records.forEach((row) => {
        if (this.selectedRowKeys.indexOf(row.rowKey) <= -1) {
          list.push(row)
        }
      })
      this.records = list
      this.selectedRowKeys = []
      this.selectedRow = []
    },
    calcPurchaseOrderList() {
      this.showPurchaseOrderList = true
    },
    savePurchaseOrderList(type = null) {
      this.settlement.taskInfoId = this.taskInfoId
      this.settlement.details = this.records
      postAction(this.urls.save, this.settlement).then((res) => {
        if (res.success) {
          this.settlement = res.result
          this.records = this.settlement.details
          this.$messageWorkReport.success('保存成功')
          if (type == 'ok') {
            this.$emit('close')
          }
        } else {
          this.$messageWorkReport.error(res.message)
        }
      })
    },
    selected(rows) {
      this.showPurchaseOrderList = false
      this.fetchDetail(rows)
    },
    onSelectChange(selectedRowKeys, selectedRow) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRow = selectedRow
    },
    fetchDetail(datas) {
      if (datas.length > 0) {
        postAction(this.urls.loadPurchaseOrderDetail, datas).then((res) => {
          if (res.success) {
            let list = res.result
            let records = []
            for (let element of list) {
              let record = {}
              record.rowKey = this.randomString(10)
              record.purchaseOrderNum = element.EBELN
              record.contractNum = element.DOKNR
              record.lineNum = element.EBELP
              record.fundName = element.TXZ01
              record.fundAmount = element.NETPR
              record.paidAmount = element.DMBTR
              record.qualityDeposit = 0
              record.finalQualityDeposit = 0
              record.unpaidAmount = 0
              records.push(record)
            }
            this.records = records
          }
        })
      }
    },
    handleOk() {
      this.savePurchaseOrderList('ok')
    },
    handleCancel() {
      this.$emit('close')
    },
    randomString(len) {
      len = len || 32
      var $chars =
        'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
      var maxPos = $chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    changeSettlementType() {
      if (this.settlement.settlementType == '1') {
        this.records.forEach((r) => {
          if (
            r.qualityDeposit &&
            !isNaN(r.qualityDeposit) &&
            r.qualityDeposit > 0 &&
            this.settlement.settlementAmount &&
            !isNaN(this.settlement.settlementAmount) &&
            this.settlement.qualityDepositRatio &&
            !isNaN(this.settlement.qualityDepositRatio)
          ) {
            r.finalQualityDeposit = (
              (parseFloat(this.settlement.settlementAmount) * parseFloat(this.settlement.qualityDepositRatio)) /
              100
            ).toFixed(2)
          } else {
            r.finalQualityDeposit = 0.0
          }
        })
      }
      if (this.settlement.settlementType == '2') {
        this.records.forEach((r) => {
          r.finalQualityDeposit = r.qualityDeposit
        })
      }
      let finalQualityDeposit = 0
      this.records.forEach((r) => {
        if (r.finalQualityDeposit && !isNaN(r.finalQualityDeposit)) {
          finalQualityDeposit += parseFloat(r.finalQualityDeposit)
        } else {
          r.finalQualityDeposit = 0
        }
        if (!r.paidAmount || isNaN(r.paidAmount)) {
          r.paidAmount = 0
        }
        if (!r.unpaidAmount || isNaN(r.unpaidAmount)) {
          r.unpaidAmount = 0
        }
        if (!r.qualityDeposit || isNaN(r.qualityDeposit)) {
          r.qualityDeposit = 0
        }
      })
      this.calcTotalObj()
      if (
        this.totalObj.paidAmountTotal &&
        !isNaN(this.totalObj.paidAmountTotal) &&
        this.settlement.settlementAmount &&
        !isNaN(this.settlement.settlementAmount)
      ) {
        if (!this.settlement.deductAmount || isNaN(this.settlement.deductAmount)) {
          this.$set(this.settlement, 'deductAmount', 0)
        }
        this.$set(
          this.settlement,
          'paymentAmount',
          (
            parseFloat(this.settlement.settlementAmount) -
            parseFloat(this.settlement.deductAmount) -
            parseFloat(this.totalObj.paidAmountTotal) -
            parseFloat(this.totalObj.unpaidAmountTotal) -
            parseFloat(this.totalObj.finalQualityDepositTotal)
          ).toFixed(2)
        )
      } else {
        this.$set(this.settlement, 'paymentAmount', 0.0)
      }
      if (!this.settlement.qualityDepositRatio || isNaN(this.settlement.qualityDepositRatio)) {
        this.$set(this.settlement, 'qualityDepositRatio', 0)
      }
    },
  },
  watch: {
    showFlag(newV, oldV) {
      if (newV) {
        this.fetchSettlement()
      }
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
.page-main {
  .container {
    .content {
      margin-top: 20px;
      section {
        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
  .tips-box {
    margin-top: 32px;
    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}
.icon-file {
  background-image: url('~@assets/file.png');
}
.cr-content-pop {
  p {
    margin-bottom: 15px;
    color: #666;
    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>